<template>
  <div style="margin-left:50px;">
    <a v-show="showDownload" class="download" :href="templateUrl" title="下载">下载模板</a>
    <el-upload
      ref="upload"
      class="upload-demo"
      drag
      multiple
      :action="importApi"
      :file-list="formFileList"
      :on-exceed="formHandleExceed"
      :on-remove="formHandleRemove"
      :on-success="formHandleSuccess"
      :http-request="formHandleUpload"
      :before-upload="beforeUploadForm"
    >
      <i class="el-icon-upload"></i>
      <div v-loading="upLoading" class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div slot="tip" class="el-upload__tip">{{ tipMsg }}</div>
    </el-upload>
    <!-- 上传错误消息 -->
    <div style="color:red;margin-top:10px" v-html="errorList"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { apiRequest } from '@/api'
import * as comFunc from '@/utils/common'

export default {
  name: 'ExcelImport',
  // 上传成功触发 onSuccessClick
  props: {
    fileLimit: {
      type: Number,
      default: 1
    },
    // 上传文件大小 m
    formMaxSize: {
      type: Number,
      default: 10
    },
    // eslint-disable-next-line vue/require-default-prop
    importApi: String,
    // 模板下载路径 没有不显示下载按钮
    // eslint-disable-next-line vue/require-default-prop
    templateUrl: String,
    // 下面提示文字
    tip: {
      type: String,
      default: '请上传xls/xlsx文件，且不超过4MB'
    },
    // eslint-disable-next-line vue/require-default-prop
    param: Object,
    // eslint-disable-next-line vue/require-default-prop
    fileType: Array
  },
  data() {
    return {
      upLoading: false,
      // 显示上传文件
      formFileList: [],
      // 确定上传文件
      uploadFormFileList: [],
      header: {},
      tipMsg: '请设置tip',
      errorList: '',
      // fileType: ['xlsx', 'xls', 'jpg', 'png'],
      showDownload: true
    }
  },
  methods: {
    // 文件上传成功 使用自定义http请求此方法将不会调用
    formHandleSuccess(response, file, fileList) {
      this.upLoading = false
      this.tipMsg = response.message + '<br />' + '123 123'
      var thisVue = this

      // setTimeout(() => {
      //   this.$refs.upload.clearFiles()
      // }, 1500)

      // console.log(response)
      // 回调使用者绑定的方法
      this.$emit('success', response, function(msg) {
        thisVue.tipMsg = msg
      })
    },
    // 开始上传前验证
    beforeUploadForm(file) {
      this.upLoading = true

      // console.log(file)
      // return

      // 验证文件大小
      if (file.size / 1024 / 1024 > this.formMaxSize) {
        this.$message({
          message: `上传文件大小不能超过${this.formMaxSize}MB!`,
          type: 'error'
        })
        this.upLoading = false
        return false
      }

      // 中文乱码处理
      if (file.raw) {
        const reader = new FileReader() // 读取文件内容
        reader.readAsText(file.raw, 'gb2312') // 防止中文乱码问题，不加reader.onload方法都不会触发
        reader.onload = function(e) {
          this.contentHtml = e.target.result // txt文本内容，接下来就可以对其进行校验处理了
        }
      }
      // 验证文件类型
      if (!this.fileType) {
        return
      }
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      var typeCheck = false
      for (let i = 0; i < this.fileType.length; i++) {
        const element = this.fileType[i]
        if (element.toUpperCase() === testmsg.toUpperCase()) {
          typeCheck = true
          break
        }
      }
      if (!typeCheck) {
        this.upLoading = false
        this.$message({ message: '上传文件只能是' + comFunc.Array2String(this.fileType, ',', true) + '格式!', type: 'warning' })
      }
      return typeCheck
    },
    // 移除上传列表中文件
    formHandleRemove(file, formFileList) {
      // console.log(file)
      // console.log(formFileList)
      // return

      const thiz = this
      for (let i = 0; i < thiz.uploadFormFileList.length; i++) {
        if (thiz.uploadFormFileList[i].pname === file.name) {
          thiz.uploadFormFileList.splice(i, 1)
          break
        }
      }
    },
    // 允许上传文件个数验证
    formHandleExceed(files, formFileList) {
      // console.log(files)
      // console.log(formFileList)
      // return
      // this.$message.warning(
      //   `当前限制选择 1 个文件，本次选择了 ${
      //     files.length
      //   } 个文件，共选择了 ${files.length + formFileList.length} 个文件`
      // )
    },
    // 上传文件处理 相关文档https://blog.csdn.net/qq_34971175/article/details/84107723
    async formHandleUpload(uploadFileParam) {
      // console.log(param)
      // return

      const formData = new FormData()
      formData.append('file', uploadFileParam.file)
      var resp = await apiRequest(this.importApi, null, 'POST', this, 'upLoading', 2, this.param, formData)
      // console.log(resp)
      if (resp.ok) {
        // 回调使用者绑定的方法
        this.$emit('success', resp)
        this.tipMsg = resp.message
        uploadFileParam.onSuccess() // 上传成功的图片会显示绿色的对勾
      } else {
        uploadFileParam.onError()
        // 输出错误消息
        this.tipMsg = resp.message
        this.errorList = ''
        resp.body.error.simpleMessage.forEach(element => {
          this.errorList += element + '<br />'
        })
      }

      // // 使用axios
      // const thiz = this
      // const formData = new FormData()
      // formData.append('uid', '上传文件编号') // 额外参数
      // formData.append('files', param.file)
      // const loading = thiz.$loading({
      //   lock: true,
      //   text: '上传中，请稍候...',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.7)'
      // })
      // console.log('执行thiz.$axios')
      // thiz.$axios.post('http://localhost:8080/upload/file', formData).then(({ data }) => {
      //   if (data.statusCode === 233) {
      //     thiz.$message('上传文件成功，' + data.message)
      //     thiz.formFileList = []
      //     thiz.uploadFormFileList = []
      //   } else {
      //     thiz.formFileList = []
      //     thiz.uploadFormFileList = []
      //     thiz.$message('上传文件失败，' + data.message)
      //   }
      //   loading.close()
      // })
    }
  },
  // eslint-disable-next-line vue/order-in-components
  computed: {
    ...mapState(['user'])
  },
  // eslint-disable-next-line vue/order-in-components
  mounted() {
    this.tipMsg = this.tip

    // 设置请求头token
    // console.log(this.loginInfo)
    // if (this.user.token) {
    //   this.header.uId = this.user.uId
    //   this.header.token = this.user.token
    // }

    if (!this.importApi) {
      console.log('请输入importApi')
    }
    if (!this.templateUrl) {
      this.showDownload = false
      // console.log('请输入templateUrl')
    }
    // if (!this.param) {
    //   console.log('请输入param')
    // }
  }
}
</script>
<style lang="scss" scoped>
.download {
  width: 65px;
  color: blue;
  display: block;
  margin-bottom: 10px;
  text-decoration: underline;
}
</style>
